package pt.iscte.dcti.pa.controller;

//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import pt.iscte.dcti.pa.view.*;
import pt.iscte.dcti.pa.model.*;

public class WorksheetController implements Observer {
	private WorksheetView theView;
	private WorksheetModel theModel;

	public WorksheetController(WorksheetView theView, WorksheetModel theModel) {
		this.theView = theView;
		this.theModel = theModel;

		this.theView.addObserver(this);
		this.theModel.addObserver(this.theView.getMatriz());
	}
	
	public void updateColabValue(int abscissa, int oordinate, String value) throws NumberFormatException, Exception {
		boolean propagateValue = false;
		String result;
		result = this.theModel.changeState(abscissa, oordinate, value, propagateValue);
	}
	
	public void lockCell(int abscissa, int ordinate) {
		boolean sussess;
		sussess = this.theView.lockCell(abscissa, ordinate);
	}
	
	@Override
	public void update(Observable o, Object arg) {
		
		VisibleElement ve = (VisibleElement)o;		
		int xx, yy;		
		String value;
		
		try {

			xx = ve.getXX();
			yy = ve.getYY();			
			
			
			String newValue;
			if (arg != null && ((boolean)arg)) {
				newValue = theModel.getCellValue(xx, yy);
			}
			else {
				boolean propagateValue = true;
				value = ve.getValue();
				newValue = theModel.changeState(xx, yy, value, propagateValue);
			}
			
			//Actualizar View
			//if (newValue != null) {
				//theView.setCellText(xx, yy, newValue);
			//}
		}

		catch (NumberFormatException ex) {

			System.out.println(ex);
			//theView.displayErrorMessage("You Need to Enter 2 Integers");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
	}
}
